<template>
  <div class="distributor-analytics">
    <!-- 标题区域 -->
    <div class="header">
      <h1>分销商业绩分析</h1>
      <div class="filter-area">
        <div class="level-filter">
          <select v-model="selectedLevel" @change="fetchData">
            <option value="">所有等级</option>
            <option value="standard">标准分销商</option>
            <option value="premium">高级分销商</option>
            <option value="vip">VIP分销商</option>
          </select>
        </div>
        <div class="time-filter">
          <input type="date" v-model="startDate" @change="fetchData">
          <span>至</span>
          <input type="date" v-model="endDate" @change="fetchData">
        </div>
        <button class="refresh-btn" @click="fetchData">
          <i class="fas fa-sync-alt"></i>
          刷新数据
        </button>
      </div>
    </div>

    <!-- 概览卡片区域 -->
    <div class="overview-cards">
      <div class="card" v-for="card in overviewData" :key="card.title">
        <div class="card-icon">
          <i :class="card.icon"></i>
        </div>
        <div class="card-content">
          <div class="card-title">{{ card.title }}</div>
          <div class="card-value">{{ formatNumber(card.value) }}{{ card.unit }}</div>
          <div class="card-growth" :class="card.growth >= 0 ? 'positive' : 'negative'">
            <i :class="card.growth >= 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'"></i>
            {{ Math.abs(card.growth) }}%
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 分销商业绩对比图表 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>业绩对比</h3>
          <div class="chart-filter">
            <button 
              v-for="option in metricOptions" 
              :key="option.value"
              :class="['chart-filter-btn', { active: selectedMetric === option.value }]"
              @click="selectedMetric = option.value"
            >
              {{ option.label }}
            </button>
          </div>
        </div>
        <div class="chart-container" ref="comparisonChartRef"></div>
      </div>

      <!-- 分销商业绩趋势图表 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>业绩趋势</h3>
          <div class="chart-filter">
            <button 
              v-for="option in periodOptions" 
              :key="option.value"
              :class="['chart-filter-btn', { active: selectedPeriod === option.value }]"
              @click="selectedPeriod = option.value"
            >
              {{ option.label }}
            </button>
          </div>
        </div>
        <div class="chart-container" ref="trendChartRef"></div>
      </div>
    </div>

    <!-- 分销商排行表格 -->
    <div class="ranking-card">
      <div class="ranking-header">
        <h3>分销商排名</h3>
        <div class="ranking-actions">
          <button class="download-btn">
            <i class="fas fa-download"></i>
            导出数据
          </button>
        </div>
      </div>
      
      <div class="table-container">
        <table class="ranking-table">
          <thead>
            <tr>
              <th>排名</th>
              <th>分销商</th>
              <th>等级</th>
              <th class="sortable" @click="handleSort('sales')">
                销售额
                <i class="fas" :class="getSortIconClass('sales')"></i>
              </th>
              <th class="sortable" @click="handleSort('orders')">
                订单量
                <i class="fas" :class="getSortIconClass('orders')"></i>
              </th>
              <th class="sortable" @click="handleSort('commission')">
                佣金
                <i class="fas" :class="getSortIconClass('commission')"></i>
              </th>
              <th class="sortable" @click="handleSort('customers')">
                客户数
                <i class="fas" :class="getSortIconClass('customers')"></i>
              </th>
              <th class="sortable" @click="handleSort('growth')">
                环比增长
                <i class="fas" :class="getSortIconClass('growth')"></i>
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(distributor, index) in sortedDistributors" :key="distributor.id">
              <td class="rank">{{ index + 1 }}</td>
              <td class="distributor-info">
                <div class="avatar">
                  <img :src="distributor.avatar" :alt="distributor.name">
                </div>
                <div class="info">
                  <div class="name">{{ distributor.name }}</div>
                  <div class="id">ID: {{ distributor.id }}</div>
                </div>
              </td>
              <td>
                <span class="level-tag" :class="getLevelClass(distributor.level)">
                  {{ getLevelText(distributor.level) }}
                </span>
              </td>
              <td class="sales">¥{{ formatNumber(distributor.sales) }}</td>
              <td>{{ distributor.orders }}</td>
              <td class="commission">¥{{ formatNumber(distributor.commission) }}</td>
              <td>{{ distributor.customers }}</td>
              <td :class="distributor.growth >= 0 ? 'positive' : 'negative'">
                <i :class="distributor.growth >= 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'"></i>
                {{ Math.abs(distributor.growth) }}%
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import * as echarts from 'echarts/core';
import { BarChart, LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { generateDistributorAnalyticsData } from '@/utils/agentMock';

// 注册必要的ECharts组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  CanvasRenderer
]);

// 图表容器引用
const comparisonChartRef = ref<HTMLElement | null>(null);
const trendChartRef = ref<HTMLElement | null>(null);
let comparisonChart: echarts.ECharts | null = null;
let trendChart: echarts.ECharts | null = null;

// 筛选和排序状态
const selectedLevel = ref('');
const startDate = ref('');
const endDate = ref('');
const selectedMetric = ref('sales');
const selectedPeriod = ref('day');
const sortField = ref('sales');
const sortOrder = ref('desc');

// 数据状态
const analyticsData = ref<any>(null);
const loading = ref(true);

// 业绩指标选项
const metricOptions = [
  { label: '销售额', value: 'sales' },
  { label: '订单量', value: 'orders' },
  { label: '佣金', value: 'commission' },
  { label: '客户数', value: 'customers' }
];

// 时间周期选项
const periodOptions = [
  { label: '日', value: 'day' },
  { label: '周', value: 'week' },
  { label: '月', value: 'month' }
];

// 概览卡片数据
const overviewData = computed(() => {
  if (!analyticsData.value) return [];
  
  return [
    {
      title: '活跃分销商',
      value: analyticsData.value.overview.activeDistributors,
      unit: '',
      growth: analyticsData.value.overview.activeDistributorsGrowth,
      icon: 'fas fa-users'
    },
    {
      title: '平均销售额',
      value: analyticsData.value.overview.averageSales,
      unit: '元',
      growth: analyticsData.value.overview.averageSalesGrowth,
      icon: 'fas fa-shopping-cart'
    },
    {
      title: '平均订单数',
      value: analyticsData.value.overview.averageOrders,
      unit: '单',
      growth: analyticsData.value.overview.averageOrdersGrowth,
      icon: 'fas fa-file-invoice'
    },
    {
      title: '平均佣金',
      value: analyticsData.value.overview.averageCommission,
      unit: '元',
      growth: analyticsData.value.overview.averageCommissionGrowth,
      icon: 'fas fa-money-bill-wave'
    }
  ];
});

// 排序后的分销商数据
const sortedDistributors = computed(() => {
  if (!analyticsData.value) return [];
  
  return [...analyticsData.value.distributors].sort((a, b) => {
    const aValue = a[sortField.value];
    const bValue = b[sortField.value];
    
    return sortOrder.value === 'asc' 
      ? aValue - bValue 
      : bValue - aValue;
  });
});

// 获取数据
const fetchData = async () => {
  loading.value = true;
  
  try {
    // 实际项目中这里会调用API获取数据
    analyticsData.value = await generateDistributorAnalyticsData({
      level: selectedLevel.value,
      startDate: startDate.value,
      endDate: endDate.value,
      period: selectedPeriod.value
    });
    
    initCharts();
  } catch (error) {
    console.error('获取分销商业绩分析数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 初始化图表
const initCharts = () => {
  initComparisonChart();
  initTrendChart();
};

// 初始化业绩对比图表
const initComparisonChart = () => {
  if (!comparisonChartRef.value) return;
  
  if (comparisonChart) {
    comparisonChart.dispose();
  }
  
  comparisonChart = echarts.init(comparisonChartRef.value);
  
  const distributors = analyticsData.value.comparison.map((item: any) => item.name);
  const metricData = analyticsData.value.comparison.map((item: any) => item[selectedMetric.value]);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: distributors,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: getMetricName(selectedMetric.value)
    },
    series: [
      {
        name: getMetricName(selectedMetric.value),
        type: 'bar',
        data: metricData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#4a6cf7' },
            { offset: 1, color: '#83a4ff' }
          ])
        }
      }
    ]
  };
  
  comparisonChart.setOption(option);
  window.addEventListener('resize', () => comparisonChart?.resize());
};

// 初始化业绩趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return;
  
  if (trendChart) {
    trendChart.dispose();
  }
  
  trendChart = echarts.init(trendChartRef.value);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['销售额', '订单量', '佣金']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: analyticsData.value.trends.dates
    },
    yAxis: [
      {
        type: 'value',
        name: '金额',
        axisLabel: {
          formatter: '{value} 元'
        }
      },
      {
        type: 'value',
        name: '订单量',
        axisLabel: {
          formatter: '{value} 单'
        }
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        yAxisIndex: 0,
        smooth: true,
        lineStyle: {
          width: 2,
          color: '#4a6cf7'
        },
        areaStyle: {
          opacity: 0.2
        },
        data: analyticsData.value.trends.sales
      },
      {
        name: '订单量',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        lineStyle: {
          width: 2,
          color: '#ff6b81'
        },
        areaStyle: {
          opacity: 0.2
        },
        data: analyticsData.value.trends.orders
      },
      {
        name: '佣金',
        type: 'line',
        yAxisIndex: 0,
        smooth: true,
        lineStyle: {
          width: 2,
          color: '#1dd1a1'
        },
        areaStyle: {
          opacity: 0.2
        },
        data: analyticsData.value.trends.commission
      }
    ]
  };
  
  trendChart.setOption(option);
  window.addEventListener('resize', () => trendChart?.resize());
};

// 处理表格排序
const handleSort = (field: string) => {
  if (sortField.value === field) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  } else {
    sortField.value = field;
    sortOrder.value = 'desc';
  }
};

// 获取排序图标类
const getSortIconClass = (field: string) => {
  if (sortField.value !== field) {
    return 'fa-sort';
  }
  return sortOrder.value === 'asc' ? 'fa-sort-up' : 'fa-sort-down';
};

// 获取指标名称
const getMetricName = (metric: string) => {
  const option = metricOptions.find(item => item.value === metric);
  return option ? option.label : '';
};

// 格式化数字
const formatNumber = (num: number) => {
  return num.toLocaleString('zh-CN');
};

// 获取等级样式类
const getLevelClass = (level: string) => {
  return `level-${level}`;
};

// 获取等级文本
const getLevelText = (level: string) => {
  switch (level) {
    case 'standard': return '标准';
    case 'premium': return '高级';
    case 'vip': return 'VIP';
    default: return '未知';
  }
};

// 监听选择的指标变化
watch(selectedMetric, () => {
  if (analyticsData.value) {
    initComparisonChart();
  }
});

// 监听选择的时间周期变化
watch(selectedPeriod, async () => {
  await fetchData();
});

// 组件挂载时获取数据
onMounted(() => {
  // 设置默认日期范围
  const now = new Date();
  endDate.value = now.toISOString().split('T')[0];
  
  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(now.getDate() - 30);
  startDate.value = thirtyDaysAgo.toISOString().split('T')[0];
  
  fetchData();
});
</script>

<style lang="scss" scoped>
.distributor-analytics {
  padding: 24px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    @media (max-width: 768px) {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
    }
    
    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
    }
    
    .filter-area {
      display: flex;
      gap: 16px;
      align-items: center;
      
      @media (max-width: 768px) {
        flex-wrap: wrap;
        width: 100%;
      }
      
      select, input {
        padding: 8px 12px;
        border: 1px solid #e1e5eb;
        border-radius: 6px;
        font-size: 14px;
      }
      
      .time-filter {
        display: flex;
        align-items: center;
        gap: 8px;
      }
      
      .refresh-btn {
        background-color: #4a6cf7;
        color: white;
        border: none;
        border-radius: 6px;
        padding: 8px 16px;
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
        
        &:hover {
          background-color: darken(#4a6cf7, 10%);
        }
        
        i {
          font-size: 14px;
        }
      }
    }
  }
  
  .overview-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 24px;
    
    @media (max-width: 1200px) {
      grid-template-columns: repeat(2, 1fr);
    }
    
    @media (max-width: 640px) {
      grid-template-columns: 1fr;
    }
    
    .card {
      background-color: white;
      border-radius: 12px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      padding: 20px;
      display: flex;
      align-items: center;
      
      .card-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        background-color: rgba(74, 108, 247, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        
        i {
          font-size: 20px;
          color: #4a6cf7;
        }
      }
      
      .card-content {
        flex: 1;
        
        .card-title {
          font-size: 14px;
          color: #6c757d;
          margin-bottom: 6px;
        }
        
        .card-value {
          font-size: 24px;
          font-weight: 600;
          color: #2f3542;
          margin-bottom: 6px;
        }
        
        .card-growth {
          font-size: 14px;
          display: flex;
          align-items: center;
          gap: 6px;
          
          &.positive {
            color: #28a745;
          }
          
          &.negative {
            color: #dc3545;
          }
          
          i {
            font-size: 12px;
          }
        }
      }
    }
  }
  
  .charts-container {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 24px;
    
    @media (max-width: 992px) {
      grid-template-columns: 1fr;
    }
  }
  
  .chart-card, .ranking-card {
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    padding: 20px;
    
    .chart-header, .ranking-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
      }
      
      .chart-filter {
        display: flex;
        gap: 8px;
        
        .chart-filter-btn {
          padding: 6px 12px;
          border: 1px solid #e1e5eb;
          border-radius: 6px;
          background-color: white;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.3s;
          
          &:hover {
            background-color: #f8f9fa;
          }
          
          &.active {
            background-color: #4a6cf7;
            border-color: #4a6cf7;
            color: white;
          }
        }
      }
      
      .ranking-actions {
        .download-btn {
          background-color: transparent;
          border: 1px solid #e1e5eb;
          border-radius: 6px;
          padding: 6px 12px;
          font-size: 14px;
          display: flex;
          align-items: center;
          gap: 8px;
          cursor: pointer;
          
          &:hover {
            background-color: #f8f9fa;
          }
          
          i {
            font-size: 14px;
          }
        }
      }
    }
    
    .chart-container {
      height: 360px;
    }
  }
  
  .table-container {
    overflow-x: auto;
    
    .ranking-table {
      width: 100%;
      border-collapse: collapse;
      
      th, td {
        padding: 12px 16px;
        text-align: left;
        border-bottom: 1px solid #e1e5eb;
        
        &.sortable {
          cursor: pointer;
          
          &:hover {
            background-color: #f8f9fa;
          }
        }
      }
      
      th {
        font-weight: 600;
        color: #2f3542;
        background-color: #f8f9fa;
        white-space: nowrap;
        
        i {
          margin-left: 4px;
        }
      }
      
      .rank {
        font-weight: 600;
      }
      
      .distributor-info {
        display: flex;
        align-items: center;
        
        .avatar {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          overflow: hidden;
          margin-right: 12px;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
        
        .info {
          .name {
            font-weight: 500;
          }
          
          .id {
            font-size: 12px;
            color: #6c757d;
          }
        }
      }
      
      .level-tag {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        
        &.level-standard {
          background-color: rgba(38, 222, 129, 0.1);
          color: #26de81;
        }
        
        &.level-premium {
          background-color: rgba(74, 108, 247, 0.1);
          color: #4a6cf7;
        }
        
        &.level-vip {
          background-color: rgba(255, 107, 129, 0.1);
          color: #ff6b81;
        }
      }
      
      .sales, .commission {
        font-weight: 500;
      }
      
      .positive {
        color: #28a745;
      }
      
      .negative {
        color: #dc3545;
      }
    }
  }
}
</style> 